//
//  SbwjlbVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/11.
//

import UIKit

class SbwjlbVC: BaseVC {

    var collectionView: UICollectionView!
    
    var dataArray: [String] = []
    
    var ddatas: NSMutableData = NSMutableData()
    
    var allB4Data: String = ""
    var allB5Data: String = ""
    
    var isFile: Bool = true
    var navi_title: String = "设备文件列表"
    var isDownloadStart: Bool = false
    var downloadName: String = ""
    
    var isJscjVShow: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        NotificationCenter.default.addObserver(self, selector: #selector(self.onOffLine(_:)), name: NSNotification.Name(rawValue: "ON_OFF_LINE"), object: nil)
        
        if navi_title == "设备文件列表" {
            EWEBluetooth.lgf.sbwj()
            NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataB4(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_B4"), object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataB4END(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_B4_END"), object: nil)
        } else {
            if isFile {
                NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataB5(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_B5"), object: nil)
                NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataB5END(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_B5_END"), object: nil)
                NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataB6(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_B6"), object: nil)
                NotificationCenter.default.addObserver(self, selector: #selector(self.getDeviceDataB6END(_:)), name: NSNotification.Name(rawValue: "GET_DEVICE_DATA_B6_END"), object: nil)
                sbwjwj(navi_title)
            }
        }
        
    }
    
    deinit {
        SVProgressHUD.dismiss()
        sbwjwjnr("0")
    }
    
    // 获取设备某个文件夹文件列表
    func sbwjwj(_ name: String) {
        if name.count == 0 {
            return
        }
        var file_name_16 = ""
        name.forEach { (c) in
            let number = stringToAscii(c)
            file_name_16 += String(number ,radix:16)
        }
        let file_count = name.count > 10 ? name.count.description : ("0" + name.count.description)
        let file_name_16_left = "B5" + file_count + file_name_16
        var ff = 0
        getStrCountArray(file_name_16_left, 2).forEach { (str) in
            ff += changeToInt(str)
        }
        let cs = String(ff % 256, radix:16)
        let file_name_all = file_name_16_left + cs + "00"
        // 发送合成好的指令
        SVProgressHUD.show()
        EWEBluetooth.lgf.sbwjwj(file_name_all)
    }
    
    // 拉取设备某个文件
    func sbwjwjnr(_ name: String) {
        downloadName = name
        if name.count == 0 {
            return
        }
        var file_name_16 = ""
        name.forEach { (c) in
            let number = stringToAscii(c)
            file_name_16 += String(number ,radix:16)
        }
        let file_count = String(name.count, radix:16)
        let file_name_16_left = "B6" + (file_count.count == 1 ? ("0" + file_count) : file_count) + file_name_16
        var ff = 0
        getStrCountArray(file_name_16_left, 2).forEach { (str) in
            ff += changeToInt(str)
        }
        let cs = String(ff % 256, radix:16)
        let file_name_all = file_name_16_left + cs + "00"
        EWEBluetooth.lgf.sbwjwjnr(file_name_all)
    }
    
    func clearData() {
        ddatas.resetBytes(in: NSMakeRange(0, ddatas.count))
        ddatas.length = 0
    }
}

extension SbwjlbVC {
    @objc func onOffLine(_ noti: NSNotification) {
        if let isOffLine = noti.object as? Bool {
            if isOffLine && !isJscjVShow {
                self.navigationController?.viewControllers.forEach({ (vc) in
                    if vc is SbVC {
                        self.navigationController?.popToViewController(vc, animated: false)
                    }
                })
            }
        }
    }
    
    @objc func getDeviceDataB4(_ noti: NSNotification) {
        if let data = noti.object as? String {
            allB4Data += data
        }
    }
    
    @objc func getDeviceDataB4END(_ noti: NSNotification) {
        if let data = noti.object as? String {
            allB4Data += data
            let fileStr = String.init(data: allB4Data.hexData()!, encoding: .utf8) ?? ""
            let files = fileStr.split(separator: "\0")
            if files.count == 0 {
                return
            }
            dataArray.removeAll()
            files.forEach { (str) in
                dataArray.append(String(str))
            }
            collectionView.reloadData()
            debugPrint(dataArray)
            DispatchQueue.main.async {
                SVProgressHUD.dismiss()
            }
        }
    }
    
    @objc func getDeviceDataB5(_ noti: NSNotification) {
        if let data = noti.object as? String {
            allB5Data += data
        }
    }
    
    @objc func getDeviceDataB5END(_ noti: NSNotification) {
        if let data = noti.object as? String {
            allB5Data += data
            let fileStr = String.init(data: allB5Data.hexData()!, encoding: .utf8) ?? ""
            let files = fileStr.split(separator: "\0")
            if files.count == 0 {
                return
            }
            dataArray.removeAll()
            files.forEach { (str) in
                dataArray.append(String(str))
            }
            collectionView.reloadData()
            debugPrint(dataArray)
            DispatchQueue.main.async {
                SVProgressHUD.dismiss()
            }
        }
    }
    
    @objc func getDeviceDataB6(_ noti: NSNotification) {
        if !isDownloadStart {
            SVProgressHUD.show()
            isDownloadStart = true
        }
        if let data = noti.object as? String {
            let pcmData: Data = (data.hexaData)
            ddatas.append(pcmData)
        }
    }

    @objc func getDeviceDataB6END(_ noti: NSNotification) {
        if isDownloadStart {
            SVProgressHUD.dismiss()
            isDownloadStart = false
        }
        SVProgressHUD.showSuccess(downloadName + "下载完成")
        Timer.lgf_After(S: 1.0) {
            self.isJscjVShow = true
            JscjV.init().show(self.view) { [weak self] (data) in
                self?.isJscjVShow = false
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ON_OFF_LINE"), object: EWEBluetooth.lgf.isOffLine)
                if data.count == 0 {
                    self?.clearData()
                    return
                }
                // 保存则临时 pcm 文件拷贝至新（PCM）路径并转换成 wav 保存新（WAV）路径
                // 文件处理完毕，将路径（pcm_path， wav_path）保存至本地数据数组
                let pcmfileName = "/听诊样本记录-" + Date.init().lgf_TimeStampString() + ".pcm"
                let pcmfilePath = LGF_Documents_PCM + pcmfileName;
                let fileUrl = URL.init(fileURLWithPath: pcmfilePath)
                do {
                    try self?.ddatas.write(to: fileUrl)
                    let wavfileName = "/听诊样本记录-" + Date.init().lgf_TimeStampString() + ".wav";
                    let wavfilePath = LGF_Documents_WAV + wavfileName;
                    let success = EWEAudio.pcm2Wav(pcmfilePath, outPath: wavfilePath, isDeleteSourchFile: false)
                    if success {
                        var dataMap = data
                        dataMap["pcm_path"] = pcmfileName
                        dataMap["wav_path"] = wavfileName
                        dataMap["time"] = Date.init().lgf_TimeStampString()
                        dataMap["type"] = "设备下载文件"
                        dataMap["state"] = "2"
                        dataMap["name"] = self?.downloadName
                        var wavDataArray = UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? []
                        wavDataArray.append(dataMap)
                        UserDefaults.standard.setValue(wavDataArray, forKey: LGF_BD_WAV_ARRAY)
                        SVProgressHUD.showSuccess("数据保存成功")
                        self?.collectionView.reloadData()
                        Timer.lgf_After(S: 0.2) {
                            self?.clearData()
                        }
                    } else {
                        self?.removePcm(pcmfilePath)
                        self?.removePcm(wavfilePath)
                        SVProgressHUD.showError("本地数据存在异常，已自动清理缓存，请重新录音")
                        self?.clearData()
                    }
                } catch {
                    self?.removePcm(pcmfilePath)
                    SVProgressHUD.showError("本地数据存在异常，已自动清理缓存，请重新录音")
                    self?.clearData()
                    debugPrint(error)
                }
            }
        }
    }
    
}


extension SbwjlbVC : UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 55)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: SbwjlbCell.self, for: indexPath)
        let name = dataArray[indexPath.item]
        cell.name.text = name
        cell.image_view1.image = isFile ? #imageLiteral(resourceName: "wenjianjiaguanbi") : #imageLiteral(resourceName: "yinle")
        cell.image_view2.image = #imageLiteral(resourceName: "xiazai-shi-2")
        let rdataArray: [Any] = (UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? [])
        rdataArray.forEach { (dict) in
            if let data = dict as? [String: Any] {
                if let rname = data["name"] as? String {
                    if rname == (navi_title + "/" + name) {
                        cell.image_view2.image = #imageLiteral(resourceName: "duihao@1.5x")
                    }
                }
            }
        }
        cell.image_view2.isHidden = !name.contains(".WAV")
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell: SbwjlbCell = collectionView.cellForItem(at: indexPath)! as! SbwjlbCell
        let name = dataArray[indexPath.item]
        if cell.image_view2.image == #imageLiteral(resourceName: "duihao@1.5x") {
            let rdataArray: [Any] = (UserDefaults.standard.array(forKey: LGF_BD_WAV_ARRAY) ?? [])
            rdataArray.forEach { (dict) in
                if let data = dict as? [String: Any] {
                    if let rname = data["name"] as? String {
                        if rname == (navi_title + "/" + name) {
                            let vc = BdjlxqVC()
                            vc.data = data
                            vc.delegate = self
                            self.navigationController?.show(vc, sender: self)
                        }
                    }
                }
            }
            return
        }
        if name.contains(".WAV") {
            if downloadName != name && !isDownloadStart {
                clearData()
                if isDownloadStart {
                    sbwjwjnr("0")
                }
                sbwjwjnr(navi_title + "/" + name)
            }
            return
        }
        let vc = SbwjlbVC()
        vc.isFile = true
        vc.navi_title = dataArray[indexPath.item]
        self.navigationController?.show(vc, sender: self)
    }
}

extension SbwjlbVC: BdjlxqVCDelegate {
    func deleteBdjlxq(_ data: [String : Any]) {
        self.collectionView.reloadData()
    }
}
